package com.atguigu.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet(
        urlPatterns = {"/servlet1"},
        initParams = {
                @WebInitParam(name = "keya", value = "valuea"),
                @WebInitParam(name = "keyb", value = "valueb")
        }
)
public class Servlet1 extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("--------------servletConfig----------------------");

        ServletConfig servletConfig = getServletConfig();

        //获取初始配置信息
        //根据参数名获取参数值
        String keya = servletConfig.getInitParameter("keya");

        System.out.println("keya : " + keya);

        //获取所有参数名
        //hasMoreElements 判断是否还有元素
        //nextElement 获取下一个元素
        Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();

        while (initParameterNames.hasMoreElements()) {
            String panme = initParameterNames.nextElement();
            System.out.println("pname : " + panme);
        }

        System.out.println("--------------servletContext----------------------");

        //第一种方式
        ServletContext servletContext = getServletContext();
        //第二种方式
        ServletContext servletContext1 = servletConfig.getServletContext();

        //第三种方式
        ServletContext servletContext2 = req.getServletContext();

        //对比
        System.out.println(servletContext == servletContext1);
        System.out.println(servletContext == servletContext2);

        String encoding = servletContext.getInitParameter("encoding");

        System.out.println("encoding : " + encoding);

        Enumeration<String> attributeNames = servletContext.getAttributeNames();

        while (attributeNames.hasMoreElements()) {
            String name = attributeNames.nextElement();
            System.out.println("name : " + name + "=" + servletContext.getAttribute(name));
        }

        //作为域对象，一定有API

//        servletContext.setAttribute("name", "zhangsan");
        servletContext.setAttribute("ka", "va");
        servletContext.setAttribute("ka", "vaa");

        //移除
//        servletContext.removeAttribute("ka");
    }
}
